<template>
  <div class="w-[98%]">
    <div class="filter-section">
      <div>
        <el-select style="width: 120px" v-model="filter.orderStatus" placeholder="处理状态" clearable>
          <el-option v-for="item in getEnumBySn('orderStatus')" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </div>
      <div>
        <el-select style="width: 120px" v-model="filter.indexId" clearable filterable placeholder="合作编号">
          <el-option v-for="item in EnumB" :key="item.indexId" :label="item.agencyName" :value="item.indexId" />
        </el-select>
      </div>
      <div>
        <el-input style="width: 120px" v-model="filter.indexIdLike" placeholder="合作编号" clearable></el-input>
      </div>

      <div>
        <el-input style="width: 80px" v-model="filter.nativePlace" placeholder="籍贯" clearable />
      </div>
      <div>
        <el-select style="width: 80px" v-model="filter.sex" placeholder="性别" clearable>
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </div>
      <div>
        <el-select style="width: 150px" v-model="filter.transferPhone" clearable filterable placeholder="选择转移手机号">
          <el-option v-for="item in EnumA" :key="item.phoneNo" :label="item.indexId" :value="item.id" />
        </el-select>
      </div>
      <div>
        <el-select style="width: 120px" v-model="filter.businessType" clearable filterable placeholder="业务类型">
          <el-option v-for="item in getEnumBySn('businessType')" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </div>
      <div>
        <el-date-picker style="width: 130px" type="datetime" v-model="filter.orderReceiveDateStart" value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="接单开始时间" />
      </div>
      <div>
        <el-date-picker style="width: 130px" type="datetime" v-model="filter.orderReceiveDateEnd"
          value-format="YYYY-MM-DD HH:mm:ss" placeholder="接单结束时间" />
      </div>
      <div>
        <el-select style="width: 80px" v-model="filter.trusteeshipType" clearable filterable placeholder="托管">
          <el-option v-for="item in getEnumBySn('cycleTypeEnum')" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <div>
        <el-select style="width: 100px" v-model="filter.balancePayment" clearable filterable placeholder="有无尾款">
          <el-option v-for="item in getEnumBySn('balancePayment')" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <div>
        <el-input style="width: 100px" v-model="filter.customName" placeholder="客户姓名" clearable></el-input>
      </div>

      <div style="display: flex;padding-top: 20px;">
        <el-button type="primary" @click="fetchData()">查询</el-button>
        <el-button class="m-b-20px" style="width: 120px;" type="success" @click="openDrawer('add')">新增</el-button>
      </div>


    </div>

    <el-table :data="tableData" style="width: 100%" border stripe :row-class-name="getRowClassName">
      <el-table-column label="序号" width="60" align="center">
        <template #default="{ $index }">
          {{ $index + 1 }} <!-- 使用 $index 计算序号 -->
        </template>
      </el-table-column>
      <el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label"
        :width="column.width" :align="column.align" :show-overflow-tooltip="true">
        <template #default="{ row }">
          <div :style="{ backgroundColor: column.prop === 'indexId' ? row.indexIdColor : '' }">
            <div :class="{
            'red-background': column.prop === 'orderStatus' && (row.orderStatus === '暂停(有群)' || row.orderStatus === '已取消'),
            'green-background': column.prop === 'orderStatus' && (row.orderStatus === '已完成'),
            'green-dayao': column.prop === 'orderStatus' && (row.orderStatus === '定期维护'),
          }">
              {{ row[column.prop] }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" fixed="right" align="center">
        <template v-slot="scope">
          <el-button type="primary" @click="openDrawer('edit', scope.row)" size="mini">编辑</el-button>
          <!-- <el-button type="danger" @click="deleteItem(scope.row.id)" size="mini">删除</el-button> -->
          <el-button type="warning" @click="openDrawerS(scope.row)" size="mini">费用明细</el-button>
          <el-button type="success" @click="openTask(scope.row)" size="mini">任务管理</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination :current-page="currentPage" :page-size="pageSize" :total="totalItems" @current-change="currentChange"
      background layout="total,prev, pager, next" class="pagination" prev-text="上一页" next-text="下一页"></el-pagination>

    <drawer-component v-if="drawerVisible" :currentItem="currentItem" :EnumA="EnumA" :EnumB="EnumB" @close="closeDrawer"
      @save="saveItem" />

    <PayDetail ref="payDetailRef"></PayDetail>
    <TaskModel ref="taskRef" ></TaskModel>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import DrawerComponent from './UserManagement.vue'; // 引入子组件
import PayDetail from "./pay/consult/index.vue"
import request from '@/config/axios'
import { getEnumBySn } from "@/api/enums";
import TaskModel from './task/modal.vue'
const filter = ref({
  name: '',
  phone: '',
  gender: '',
  transferPhone: '',
  indexId: '',
});

// 监听 filter 对象的变化
watch(filter, (newValue, oldValue) => {
  fetchData();
}, { deep: true }); // 使用 deep 选项以便监听嵌套属性的变化


const payPend = ref('');
const payTotal = ref('');

const orderId = ref({});

const tableData = ref([]);
const EnumA = ref([]);
const EnumB = ref([]);
const dialogVisible = ref(false)
const taskRef = ref(null)
const columns = ref([
  { prop: 'orderStatus', label: '处理状态', width: '100', align: 'center' },
  { prop: 'indexId', label: '合作编号', width: '100', align: 'center' },
  { prop: 'customName', label: '客户姓名', width: '100', align: 'center' },
  { prop: 'sex', label: '性别', width: '60', align: 'center' },
  { prop: 'businessType', label: '业务类型', width: '100', align: 'center' },

  { prop: 'phoneCode', label: '转接手机号', width: '220', },
  { prop: 'trusteeshipType', label: '托管', width: '60', align: 'center' },

  // { prop: 'platform', label: '处理平台', width: '60' },
  // { prop: 'customerDemand', label: '客户诉求', width: '100' },
  { prop: 'orderReceiveDate', label: '接单日期', width: '90', align: 'center' },
  { prop: 'orderEndDate', label: '结束日期', width: '90', align: 'center' },
  { prop: 'reminderTime', label: '提醒日期', width: '90',align: 'center'},
  // { prop: 'handleStaffAccount', label: '做单员工账号', width: '110' },
  { prop: 'balancePayment', label: '有无尾款', width: '100', align: 'center' },
  { prop: 'platformMemo', label: '平台备注', width: '150', align: 'center' },
  { prop: 'memo', label: '备注', width: '260', align: 'center' },
  { prop: 'nativePlace', label: '籍贯', width: '100', align: 'center' },

]);

function getRowClassName(row) {
  return 'red-background'
}
const tableDatass = ref([]);
const totalItems = ref(0);
const currentPage = ref(1);
const pageSize = ref(15);

const drawerVisible = ref(false);

const currentItem = ref({});
const actionType = ref('');

const currentChange = (v) => {
  currentPage.value = v
  fetchData()
}
async function fetchData() {
  console.log('filter', filter.value);

  try {
    const response = await request.get({
      url: '/order/list',
      params: { ...filter.value, current: currentPage.value, size: pageSize.value }
    })
    console.log(response, 'response');
    tableData.value = response.records
    totalItems.value = response.total
    currentPage.value = response.current

  } catch (error) {
    throw error;
  } finally {
  }
}
async function listAllByParent() {
  try {
    const response = await request.get({
      url: '/payDetail/listAllByParentId',
      params: { orderId: currentItem.value.id }
    })

    tableDatass.value = response.payDetailVoList
    payPend.value = response.payPend
    payTotal.value = response.payTotal


  } catch (error) {
    throw error;
  } finally {
  }
}
async function saveRenew() {
  try {
    await request.post({
      url: "/order/save",
      data: {
        item
      }
    })
    ElMessage.success("新增成功!renew.value")
    fetchData()
    dialogVisible.value = false
  } catch (error) {
    throw error;
  } finally {

  }
}
function openDrawer(action, item = {}) {
  console.log('--触发了--');
  actionType.value = action;
  currentItem.value = { ...item };
  drawerVisible.value = true;
}

function closeDrawer() {
  drawerVisible.value = false;
}

const payDetailRef = ref({})

async function openDrawerS(item) {
  payDetailRef.value.open(item)
}

function closeDrawerS() {
  dialogVisible.value = false;
}


async function saveItem(item) {
  console.log(item.value);

  if (actionType.value === 'add') {
    try {
      await request.post({
        url: "/order/save",
        data: item.value
      })
      ElMessage.success("新增成功!")
      fetchData()
      closeDrawer();
    } catch (error) {
      throw error;
    } finally {

    }

  } else if (actionType.value === 'edit') {
    try {
      await request.post({
        url: "/order/updateById",
        data: item.value
      })
      ElMessage.success("保存成功!")
      fetchData()
      closeDrawer();
    } catch (error) {
      throw error;
    } finally {

    }
  }

}

async function deleteItem(id) {
  try {
    await request.delete({
      url: "/order/deleteById",
      data: { id: id }
    })
    fetchData()
    ElMessage.success("删除成功!")
  } catch (error) {
    throw error;
  } finally {

  }
}

const fetchEnumList = async () => {
  try {
    const responseB = await request.get({
      url: '/agency/list',
    })
    const responseA = await request.get({
      url: '/transferPhone/list',
    })
    EnumB.value = responseB
    console.log('---1---',responseA);
    EnumA.value = responseA?.filter(item=>item.phoneStatus=='正常')
  } catch (error) {
    throw error;
  } finally {
  }
};

const openTask = function(row){
  taskRef.value.open(row)
}
onMounted(() => {
  fetchData(); //获取列表
  fetchEnumList() // 获取下拉列表
});
</script>

<style scoped>
.filter-section {
  display: flex;
  align-items: center;
}

.filter-section>* {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  float: right;
  font-size: 22px;
}


.form-inline .el-form-item {
  margin-right: 20px;
}

.el-table .purple-background {
  background: rgb(169, 96, 253) !important;
  color: white;
  /* 确保样式优先级 */
}
.el-table .red-background {
  background: #f53506 !important;
  color: white;
  /* 确保样式优先级 */
}
.el-table .green-background {
  background: #36f506 !important;
  color: white;
  /* 确保样式优先级 */
}

.el-table .green-dayao {
  background: #e6a23c !important;
  color: white;
  /* 确保样式优先级 */
}
</style>
